import {inject, Injectable} from '@angular/core';
import {SelfHttp} from "../http/service";
import {menuApi} from "../../api/menu";
import {Router} from "@angular/router";

@Injectable({
  providedIn: 'root'
})
export class MenuService {
  selfHttp = inject(SelfHttp);
  router = inject(Router);
  getComponentName = (component: string) => {
    const name = component.replace(/^\//, '').replace(/\/$/, '').replace(/\//g, '-').replace(/-component$/, '');
    return name.charAt(0).toUpperCase() + name.slice(1) + 'Component';
  }
  getAsyncRoutes = (menuList: any) => {
    const asyncRoutes = [];
    for (const menu of menuList) {
      // 把menu.path的第一个/去掉
      menu.path = menu.path.replace(/^\//, '');
      const route = {
        path: menu.path,
        name: menu.name,
        component: menu.component,
        meta: menu.meta,
        children: menu.children
      };
      if (menu.children && menu.children.length > 0) {
        route.children = this.getAsyncRoutes(menu.children);
      }
      asyncRoutes.push(route);
    }
    return asyncRoutes;
  }
  getMenuList () {
    return new Promise(resolve => {
      this.selfHttp.get(menuApi.menu, {}, (res: any) => {
        const config = this.router.config;
        const asyncRoutes = this.getAsyncRoutes(res);
        asyncRoutes.forEach((route: any) => {
          // @ts-ignore
          config[config.length - 1] && config[config.length - 1].children && config[config.length - 1].children.push(route);
        });
        this.router.resetConfig(config);
        resolve(res);
      });
    })
  }
}
